package com.dcxm.stu.dao.impl;

import com.dcxm.stu.bean.Student;
import com.dcxm.stu.dao.StudentDao;
import com.dcxm.stu.rowmapper.StudentRowMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * Created by young on 2017/4/4.
 *
 * @author young
 * @version 1.1
 */
@Repository
public class StudentDaoI implements StudentDao {

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public StudentDaoI(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public int insertInfo(Student student, String newFileName) {
        int row;
        //language=SQL
        String sql = "INSERT INTO t_studentinfo (username, password, telphone,pic) VALUES (?,?,?,?)";
        try {
            row = jdbcTemplate.update(sql, student.getUsername(), student.getPassword(), student.getTelphone(), newFileName);
        } catch (Exception e) {
            row = 0;
        }
        return row;
    }

    public int insertInfo(Student student) {
        int row;
        //language=SQL
        String sql = "INSERT INTO t_studentinfo (username, password, telphone) VALUES (?,?,?)";
        try {
            row = jdbcTemplate.update(sql, student.getUsername(), student.getPassword(), student.getTelphone());
        } catch (Exception e) {
            row = 0;
        }
        return row;
    }

    public int updateInfo(Student student) {
        //language=SQL
        String sql = "UPDATE t_studentinfo SET username=?,password=? WHERE telphone=?";
        Object[] param = {student.getUsername(), student.getPassword(), student.getTelphone()};
        return jdbcTemplate.update(sql, param);
    }

    public Student getUserInfo(Student student) throws Exception {
        student.setFlag(false);
        //language=SQL
        String sql = "SELECT * FROM t_studentinfo WHERE telphone=? AND password=?";
        Object[] params = new Object[]{student.getTelphone(), student.getPassword()};
        student = jdbcTemplate.queryForObject(sql,
                params, new StudentRowMapper());
        student.setFlag(true);
        return student;
    }

    public int upImg(String newFileName, String telphone) {
        String sql = "UPDATE t_studentinfo SET pic = ? WHERE telphone=? ";
        return jdbcTemplate.update(sql, newFileName, telphone);
    }
}
